package com.atguigu.day02;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @description :
 * @autor :lyh
 */
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 如果没有对算子单独设置并行度，那么算子的并行度是1
        env.setParallelism(1);

        env
                .fromElements("hello world", "hello world")
                .flatMap((String in, Collector<Tuple2<String, Integer>> out) -> {
                    String[] words = in.split(" ");
                    for (String word : words) {
                        out.collect(Tuple2.of(word, 1));
                    }
                })
                // Collector<Tuple2<String, Integer>> -> Collector<TObject>
                // 需要对 Collector 中的泛型做注解
                .returns(Types.TUPLE(Types.STRING, Types.INT))
                .keyBy(r -> r.f0)
                .reduce((accumulator, in) -> Tuple2.of(accumulator.f0, accumulator.f1 + in.f1))
                .print();

        env.execute();


    }
}
